package leetcode.code2047;

import leetcode.IDebug;
import leetcode.helper.HelpDebug;

//执行用时：1 ms, 在所有 Java 提交中击败了100.00%的用户
//
//内存消耗：38.7 MB, 在所有 Java 提交中击败了34.23%的用户
//
//通过测试用例：244 / 244
public class Solution implements IDebug {

	public int countValidWords(String sentence) {
		int ans = 0;
		char[] s = sentence.toCharArray();
		int len = s.length;
		boolean pass = true;
		int w = 0, f = 0, h = 0;
		char c = '0';
		for (int i = 0; i <= len; i++) {
			if (i != len) {
				c = s[i];
				if (!pass && c != ' ') {// 非有效且不是空格不看了
					continue;
				}
			}
			if (i == len || c == ' ') {
				if (pass) {
					if (w != 0 || f != 0) {
						ans += 1;// 空格/结尾结算且是有效token
					}
				} else {
					pass = true;
				}
				w = 0;
				f = 0;
				h = 0;
			} else {
				if (c >= '0' && c <= '9') {// 出现数字就歇了
					pass = false;
				} else if (c == '-') {
					// 连字横只能有一个 && 两头不能越界 && 两头是字母
					if (h == 0 && i - 1 >= 0 && s[i - 1] >= 'a' && s[i - 1] <= 'z' && i + 1 < len && s[i + 1] >= 'a'
							&& s[i + 1] <= 'z') {
						h += 1;
					} else {
						pass = false;// 否则就歇
					}
				} else if (c == '!' || c == '.' || c == ',') {
                    // 符号只能有一个 && (前面什么都没有 || 有一个字符 || 有一个空格) && (后面什么都没有 || 有一个空格)
					if (f == 0 && (i - 1 < 0 || (i - 1 >= 0 && (s[i - 1] >= 'a' && s[i - 1] <= 'z') || s[i - 1] == ' '))
							&& (i + 1 == len || (i + 1 < len && s[i + 1] == ' '))) {
						f += 1;
					} else {
						pass = false;// 否则就歇
					}
				} else {
					w += 1;
				}
			}
		}
		return ans;
	}


	@Override
	public void debug1() {
		HelpDebug.compare(3, this.countValidWords("cat and  dog"));

	}

	@Override
	public void debug2() {
		// TODO Auto-generated method stub
		HelpDebug.compare(0, this.countValidWords("!this  1-s b8d!"));
	}

	@Override
	public void debug3() {
		// TODO Auto-generated method stub
		HelpDebug.compare(5, this.countValidWords("alice and  bob are playing stone-game10"));
	}

	@Override
	public void debug4() {
		// TODO Auto-generated method stub
		HelpDebug.compare(6, this.countValidWords("he bought 2 pencils, 3 erasers, and 1  pencil-sharpener."));
	}

	public void debug5() {
		// TODO Auto-generated method stub
		HelpDebug.compare(7, this.countValidWords(" , wn xhx5e2  9k !  fs uc5jc  u3  f5 lj x mkkouek, .g"));
	}

	public static void main(String[] args) {
		Solution so = new Solution();
		so.debug5();
		so.debug1();
		so.debug2();
		so.debug3();
		so.debug4();
	}

}
